package com.service.impl;

import com.core.dto.ExcutorDTO;
import com.core.dto.RefrigerationDTO;
import com.core.model.xg.Excutor;
import com.core.model.xg.Refrigeration;
import com.dao.XgDao;
import com.service.XgService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author lxf
 * @date 2018/5/2 17:18
 * To change this template use Editor | File and Code Templates.
 */
@Service("xgService")
@Transactional
public class XgServiceImpl implements XgService {

    @Autowired
    private XgDao xgDao;

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public List<ExcutorDTO> findAllExcutor() {
        return ExcutorDTO.toDTOs(xgDao.findAll(Excutor.class));
    }

    @Override
    public boolean saveOrUpdateExcutor(ExcutorDTO excutorDTO) {
        if (StringUtils.isNotEmpty(excutorDTO.getId())) {
            Excutor excutor = xgDao.load(Excutor.class, excutorDTO.getId());
            if (excutor != null) {
                excutor.init(excutorDTO);
            }
        } else {
            xgDao.saveOrUpdate(excutorDTO.toExcutor(excutorDTO));
        }
        return true;
    }

    @Override
    public boolean delExcutor(String id) {
        Excutor excutor = xgDao.load(Excutor.class, id);
        if (excutor != null) {
            xgDao.delObject(excutor);
        }
        return true;
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public List<RefrigerationDTO> findAllRefrigeration() {
        return RefrigerationDTO.toDTOs(xgDao.findAllRefrigeration());
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public RefrigerationDTO findRefrigerationById(String id) {
        return RefrigerationDTO.toDTO(xgDao.load(Refrigeration.class, id));
    }

    @Override
    public boolean saveOrUpdateRefrigeration(RefrigerationDTO refrigerationDTO) {
        Refrigeration refrigeration;
        if (StringUtils.isNotEmpty(refrigerationDTO.getId())) {
            refrigeration = xgDao.load(Refrigeration.class, refrigerationDTO.getId());
        } else {
            refrigeration = new Refrigeration();
        }
        Excutor excutor = xgDao.load(Excutor.class, refrigerationDTO.getExcutorId());
        refrigeration.init(refrigerationDTO, excutor);
        xgDao.saveOrUpdate(refrigeration);
        return true;
    }

    @Override
    public boolean delRefrigeration(String id) {
        Refrigeration refrigeration = xgDao.load(Refrigeration.class, id);
        if (refrigeration != null) {
            xgDao.delObject(refrigeration);
        }
        return true;
    }
}
